import store from '../store/store';
// import router from '@/router';
import { setStore, getStore, removeStore } from './storage';
/**
 * 定义问诊中收发的数据包类型
 * @type {{logout: number, addPatientQueue: number, joinRoom: number, msgResponse: number, login: number, msgRequest: number, patientQueueList: number}}
 */
var dataType = {
    login: 1, // 登陆请求
    logout: 2, // 登出请求
    msgRequest: 3, // 发送信息
    msgResponse: 4, // 收到消息
    addPatientQueue: 5, // 【患者】申请问诊排队
    patientQueueList: 6, // 【患者】问诊中排队的患者列表
    joinRoomRequest: 7, // 医生[接诊]：请求患者进入问诊房间
    msgContent: 8, //消息中心
    outLine: 9, //问诊离线事件
    patientReceive: 10, //医生接诊病人
    cancelRequest: 11, //取消问诊排队
    updateDoctorLine: 12, //医生上下线更新事件

    // 更多事件码没有列举完……
};

var wsConnection = {
    heartbeatTime: 8000, // 心跳时间
    wsUrl: "",
    token: "",
    ws: {},
    intervalId: 0, // 心跳定时器id
    ttId: 0,
    lock: false,
    initWebSocket: function(wsUrl, token) {
        if (wsUrl) {
            this.wsUrl = wsUrl;
        }
        if (token) {
            this.token = token;
        }
        var that = this;
        this.ws = new WebSocket(this.wsUrl);
        this.ws.onopen = this.onOpen.bind(this);
        this.ws.onmessage = function(event) {
            if (typeof event.data === 'object') {
                var reader = new FileReader();
                reader.onload = function(event) {
                    var content = reader.result.trim();
                    console.log('------- 【socket content】 -----------------------', content)
                    if (content.indexOf("{") === 0) {
                        content = JSON.parse(content);
                        that.onMessage(content);
                    }
                };
                reader.readAsText(event.data);
            }
        };
        this.ws.onclose = this.onClose.bind(this);
        this.ws.onerror = this.onError.bind(this);
    },
    onOpen: function(event) {
        console.log(event,'onOpen')
        this.login();
        this.resetHeartbeat();
    },
    onMessage: function(msg) {

        if (msg.packageType == 1 && msg.packageCode == 0) {
            console.log(msg, 'msg.packageType == 1 && msg.packageCode == 0')

            /* --- test:退出登录后，清除定时器和销毁socket --- */
            this.ttId && clearTimeout(this.ttId);
            this.intervalId > 0 && clearInterval(this.intervalId);
            this.ws.close();

            // sessionStorage.clear()
            // router.push({
            //     path: '/login',
            // });

        } else {
            store.commit('webSocketMsg', msg);
        }
        // switch (msg.packageType) {
        //   case 4:
        //     this.$store.commit('accpectPatientMsg', msg)
        //     break
        //   case 6:
        //     this.$store.commit('webSocketMsg', msg)
        //     break
        //   case 7:
        //     this.$store.commit('joinInquiryPatient', msg)
        //     break
        // }
        console.log(msg, 'Connection message.');
    },
    onClose: function(evt) {
        console.log('===【close event】===', evt);

        if (evt && evt.code !== 1000) {
            this.reconnect();
        }
        // else {
        //     // wsConnection.ws.close()
        //     console.log(evt || 'close event', "Connection closed.");
        //     if (this.token) {
        //         setTimeout(() => {
        //             this.reconnect();
        //         }, 100);
        //     }
        // }
    },
    onError: function(ev) {
        this.reconnect();
    },
    login: function() {
        // 进行登录认证
        this.send(dataType.login, { token: this.token });
    },
    logout: function(data) {

        this.ttId && clearTimeout(this.ttId);
        this.intervalId > 0 && clearInterval(this.intervalId);

        this.send(2, data);

        wsConnection.ws.close();
    },

    reconnect: function() {
        if (this.lock) {
            return;
        }
        this.lock = true;
        var that = this;

        this.ttId && clearTimeout(this.ttId);

        this.ttId = setTimeout(function() {
            console.log('===【重连中...】===')
            that.initWebSocket();
            that.lock = false;
        }, 3000);
    },
    startWsHeartbeat: function() {
        var that = this;
        this.intervalId = setInterval(function() {
            //判断websocket当前状态
            // 0 ：对应常量 正在建立连接连接，还没有完成。
            // 1 ：对应常量OPEN   连接成功建立，可以进行通信。
            // 2 ：对应常量CLOSING  连接正在进行关闭握手，即将关闭。
            // 3 : 对应常量CLOSED  连接已经关闭或者根本没有建立。
            if (that.ws.readyState === 1) {
                that.ws.send("ping"); // 心跳包
                console.log('-------连接成功建立，可以进行通信-------')
            } else if (3 === that.ws.readyState) {
                that.reconnect();
            }
        }, this.heartbeatTime);
    },
    resetHeartbeat: function() {
        this.ttId && clearTimeout(this.ttId);
        this.intervalId > 0 && clearInterval(this.intervalId);
        this.startWsHeartbeat()
    },
    /**
     *
     * @param type 信息包类型
     * @param data 发送的需要发送的数据
     */
    send: function(type, data) {

        if (!data) {
            data = {};
        }
        if (type == 13) {
            console.log('=== 退出问诊 ===')
        }
        data.packageType = type;
        console.log('------- 【socket send】 -----------------------', type, data)
        if (this.ws.readyState !== 1) {
            // console.log('链接状态=' + this.ws.readyState + '不可发送消息 ' );
            return;
        }
        data = JSON.stringify(data);
        this.ws.send(data);
    },

};



// //抛出websocket对象
export default wsConnection
